<template>
  <div class="main">
    <div class="register-container">
      <el-card class="register-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h2 class="register-title">
              <el-icon class="title-icon"><UserFilled /></el-icon>
              用户注册
            </h2>
          </div>
        </template>

        <el-form
          :model="formData"
          ref="registerFormRef"
          :rules="rules"
          label-width="90px"
          size="large"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="formData.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              clearable
            />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              prefix-icon="Lock"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item label="姓名" prop="full_name">
            <el-input
              v-model="formData.full_name"
              placeholder="请输入真实姓名"
              prefix-icon="Avatar"
              clearable
            />
          </el-form-item>

          <el-form-item label="手机号码" prop="phone_number">
            <el-input
              v-model="formData.phone_number"
              placeholder="请输入手机号码"
              prefix-icon="Phone"
              clearable
            />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱地址"
              prefix-icon="Message"
              clearable
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="handleRegister"
              class="register-btn"
              :loading="loading"
              size="large"
            >
              {{ loading ? '注册中...' : '立即注册' }}
            </el-button>

            <el-button
              @click="goBack"
              class="back-btn"
              size="large"
            >
              返回登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'
import { registerApi } from '@/utils/api'

const router = useRouter()
const registerFormRef = ref()
const loading = ref(false)

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  full_name: '',
  phone_number: '',
  email: ''
})

// 自定义验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== formData.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (value === '') {
    callback(new Error('请输入手机号码'))
  } else if (!phoneRegex.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

const validateEmail = (rule, value, callback) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (value === '') {
    callback(new Error('请输入邮箱地址'))
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱地址'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  full_name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone_number: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ]
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return

    loading.value = true

    // 移除确认密码字段，不发送到后端
    const { confirmPassword, ...registerData } = formData

    const res = await registerApi(registerData)

    if (res.code === 200) {
      ElMessage.success({
        message: '注册成功，即将跳转到登录页面',
        duration: 2000,
      })

      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        router.push('/')
      }, 1500)
    } else {
      ElMessage.error({
        message: res.message || '注册失败',
        duration: 1500,
      })
    }
  } catch (error) {
    console.error('注册错误:', error)
    ElMessage.error({
      message: '网络错误，请稍后重试',
      duration: 1500,
    })
  } finally {
    loading.value = false
  }
}

// 返回登录页面
const goBack = () => {
  router.push('/')
}
</script>

<style lang="less" scoped>
.main {
  background-image: url("@/assets/bglogin.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    z-index: 1;
  }
}

.register-container {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 500px;
  margin: 0 20px;
}

.register-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;

  :deep(.el-card__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-bottom: none;
    padding: 20px;
  }

  :deep(.el-card__body) {
    padding: 30px;
    max-height: 70vh;
    overflow-y: auto;
  }
}

.card-header {
  text-align: center;
}

.register-title {
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;

  .title-icon {
    font-size: 28px;
  }
}

.register-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  margin-bottom: 10px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  }

  &:active {
    transform: translateY(0);
  }
}

.back-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .main {
    padding: 20px;
  }

  .register-container {
    max-width: 100%;
    margin: 0;
  }

  .register-card {
    :deep(.el-card__body) {
      padding: 20px;
      max-height: 80vh;
    }
  }

  .register-title {
    font-size: 20px;
  }
}

// 表单样式优化
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  &.is-focus {
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  }
}
</style>
